package com.any.hook.core.webapi.util;

import com.any.hook.common.exception.HookException;
import com.any.hook.core.webapi.config.WebApiErrorCode;
import com.any.hook.core.webapi.entity.DBInfo;

public class GenSqlUtil {
    public static String genGenTablesSql(DBInfo dbInfo) throws HookException{
        String type=dbInfo.getDriverName();
        switch (type){
            case "mysql":
                return "select table_name as name from information_schema.tables where table_schema='"+
                        dbInfo.getDbname()+"'";
            case "oracle":
                return "select table_name as name from all_tables";
            case "postgresql":
                return "select schemaname||'.'||tablename as name from pg_tables";
            case "dameng":
                return "select table_name as name from all_tables";
            default:
                throw HookException.asHookException(WebApiErrorCode.API_JSON_LOGIC_ERROR,
                        String.format("不支持 %s 类型的数据库，请联系开发人员 .",type));
        }
    }
    public static String genGenColSql(DBInfo dbInfo,String tableName) throws HookException{
        String type=dbInfo.getDriverName();
        switch (type){
            case "mysql":
                return String.format("select column_name  as name from information_schema.COLUMNS " +
                        "where table_schema='%s' and table_name='%s'",dbInfo.getDbname(),tableName);
            case "oracle":
                return String.format("select COLUMN_NAME as name from all_tab_columns " +
                        "where TABLE_NAME=upper('%s')",tableName);
            case "dameng":
                return String.format("select COLUMN_NAME from all_tab_columns where Table_Name='%s' and owner='%s'",tableName,dbInfo.getDbname().toUpperCase());
            case "postgresql":
                String[] tname=tableName.split("\\.");
                if(tname.length!=2){
                    throw HookException.asHookException(WebApiErrorCode.API_JSON_LOGIC_ERROR,
                            String.format("数据库表名称 %s 是错误的， 请联系开发人员 .",tableName));
                }
                return String.format("select column_name from information_schema.columns \n" +
                        "where table_schema in ('public','%s') and table_name='%s'",tname[0],tname[1]);
            default:
                throw HookException.asHookException(WebApiErrorCode.API_JSON_LOGIC_ERROR,
                        String.format("不支持 %s 类型的数据库，请联系开发人员 .",type));
        }
    }
}

